package com.bulletelc.apollopre.module.main.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.entity.BannerBean;
import com.bulletelc.apollopre.entity.Classify;
import com.bulletelc.apollopre.entity.ProductDetail;
import com.bulletelc.apollopre.framework.MVPBaseFragment;
import com.bulletelc.apollopre.interfaces.listener.OnItemClickListener;
import com.bulletelc.apollopre.module.cases.CaseListActivity;
import com.bulletelc.apollopre.module.display.product.details.ProductDetailsActivity;
import com.bulletelc.apollopre.module.display.product.resultList.ResultListActivity;
import com.bulletelc.apollopre.module.display.search.SearchActivity;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.module.richscan.RichScanActivity;
import com.bulletelc.apollopre.utils.BannerImageLoader;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.widget.CustomGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * author: lhl
 * time  : 2017/10/15
 * desc  : 首页界面
 */

public class HomeFragment extends MVPBaseFragment<HomeContract.View,HomePresenter> implements OnRefreshListener,
        OnLoadmoreListener, OnBannerListener , View.OnClickListener, HomeContract.View, OnItemClickListener,
        AdapterView.OnItemClickListener {

    // views
    private CustomGridView cgvClassifyFirst; // 分类入口
    private ProgressBar pbLoad;
    private Banner banner;
    private RecyclerView rvPackage;
    private SmartRefreshLayout refreshLayout;
    private AutoLinearLayout llRichScan, llClassify;
    private TextView tvSearch;

    // data
    private List<String> imageUrls;
    private List<BannerBean> bannerList;
    private int page = 1; // 产品分页
    private int packagePageCount; // 产品总页
    private List<ProductDetail> packageList;
    private PackageAdapter packageAdapter;
    private List<Classify> classifyList;
    private HomeClassifyFirstAdapter homeClassifyFirstAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay(); // 开始轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        //LogUtil.i("执行");
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay(); // 结束轮播
    }

    @Override
    public int getLayoutRes() {
        return R.layout.home_fragment;
    }

    @Override
    public void assignViews() {
        cgvClassifyFirst = v.findViewById(R.id.cgvClassifyFirst);
        pbLoad = v.findViewById(R.id.pbLoad);
        llRichScan = v.findViewById(R.id.llRichScan);
        llClassify =  v.findViewById(R.id.llClassify);
        tvSearch= v.findViewById(R.id.tvSearch);
        banner = v.findViewById(R.id.banner);
        rvPackage = v.findViewById(R.id.rvPackage);
        refreshLayout = v.findViewById(R.id.smartRefreshLayout);

//        packageList = new ArrayList<>();
//        classifyList = new ArrayList<>();
//        packageAdapter = new PackageAdapter(baseActivity,packageList);
//        homeClassifyFirstAdapter = new HomeClassifyFirstAdapter(baseActivity, classifyList);

    }

    @Override
    public void setListener() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        packageAdapter.setListener(this);
        llRichScan.setOnClickListener(this);
        llClassify.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        cgvClassifyFirst.setOnItemClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        MyUtil.setProgressBar(pbLoad, true);
        initBanner();
        initRvPackage();
        initHomeCate();
    }

    /**
     * SmartRefreshLayout 监听接口
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        refreshLayout.finishRefresh(400);
        presenter.getSliderShow();
        presenter.getHomeCate();
        presenter.getPackage(page);
    }

    /**
     * SmartRefreshLayout 监听接口
     * @param refreshlayout
     */
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        if (page <= packagePageCount) {
            presenter.getPackage(page);
        } else {
            //Toast.makeText(baseActivity, "没有更多数据", Toast.LENGTH_SHORT).show();
        }
        refreshLayout.finishLoadmore(true);
    }

    @Override
    public void OnBannerClick(int position) {
//        String productId = hotSaleList.get(position).getId();
//        Intent intent = new Intent(baseActivity, ProductDetailsActivity.class);
//        intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, productId);
//        startActivity(intent);
    }


    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    public void onSuccessSliderShow(List<BannerBean> bannerBeanList) {
        if (bannerBeanList != null && bannerBeanList.size() > 0) {
            bannerList.clear();
            bannerList.addAll(bannerBeanList);
            imageUrls.clear();
            for (int i = 0, size = bannerList.size(); i < size; i++) {
                imageUrls.add(bannerList.get(i).getImageUrl());
            }
            List<String> imageUrlss = new ArrayList<>();
            imageUrlss.addAll(imageUrls);
            banner.update(imageUrlss);
        }
    }

    @Override
    public void onFailSliderShow(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorSlideShow(String error) {

    }

    @Override
    public void onSuccessPackage(List<ProductDetail> productDetailList,int packagePageCount) {
        this.packagePageCount = packagePageCount;
        if (productDetailList != null && productDetailList.size() > 0) {
            if (page == 1) {
                packageList.clear();
            }
            packageList.addAll(productDetailList);
            packageAdapter.notifyDataSetChanged();
        } else {
            //do nothing
        }
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onFailPackage(String fail) {
        Toast.makeText(baseActivity, fail, Toast.LENGTH_SHORT).show();
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onErrorPackage(String error) {
        //ToastUtil.showLongToast(getActivity(),R.string.network_msg);
        MyUtil.setProgressBar(pbLoad, false);
    }

    @Override
    public void onSuccessHomeCate(List<Classify> classifyList) {
        if (classifyList.size() > 0) {
            this.classifyList.clear();
            this.classifyList.addAll(classifyList);
            homeClassifyFirstAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFailHomeCate(String fail) {

    }

    @Override
    public void onErrorHomeCate(String error) {

    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(baseActivity,ProductDetailsActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, packageList.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llRichScan:
                startActivity(new Intent(baseActivity,RichScanActivity.class));
                break;
            case R.id.tvSearch:
                startActivity(new Intent(baseActivity, SearchActivity.class));
                break;
            case R.id.llClassify:
                ((MainActivity) baseActivity).showClassify();
                break;
        }
    }

    /**
     * 初始化banner
     */
    private void initBanner(){
        bannerList = new ArrayList<>();
        imageUrls = new ArrayList<>();
        //设置图片集合
        banner.setImages(imageUrls);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当banner样式有显示title时）
        //banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(1000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(this);
        banner.start();
        presenter.getSliderShow();
    }

    /**
     * 初始化
     */
    private void initRvPackage() {
        packageList = new ArrayList<>();
        packageAdapter = new PackageAdapter(baseActivity,packageList);
        rvPackage.setAdapter(packageAdapter);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(baseActivity, 2);
        //layoutManager.setAutoMeasureEnabled(true);
        rvPackage.setLayoutManager(layoutManager);
        //rvPackage.setHasFixedSize(true);
        rvPackage.setNestedScrollingEnabled(false);
        //rvPackage.addItemDecoration(new DividerGridItemDecoration(baseActivity));
         presenter.getPackage(1);
    }
    /**
     * 初始化首页分类
     */
    private void initHomeCate() {
        classifyList = new ArrayList<>();
        homeClassifyFirstAdapter = new HomeClassifyFirstAdapter(baseActivity, classifyList);
        cgvClassifyFirst.setAdapter(homeClassifyFirstAdapter);
        presenter.getHomeCate();
    }

    /**
     * 含有"定制"的分类去到定制案例
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String name = classifyList.get(i).getLabel();
        if (name.contains("定制")) {
            startActivity(new Intent(baseActivity, CaseListActivity.class));
            return;
        }
        String ids = classifyList.get(i).getIds();
        Intent intent = new Intent(baseActivity, ResultListActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_CLASSIFY_ID, ids);
        baseActivity.startActivity(intent);
    }

}
